package com.web3.management.controller;

import com.web3.management.dto.ApiResponse;
import com.web3.management.dto.request.BindClientRequest;
import com.web3.management.dto.request.CommandCreateRequest;
import com.web3.management.dto.response.AccountCredentialLogResponse;
import com.web3.management.dto.response.ClientBindingResponse;
import com.web3.management.entity.AccountCredentialLog;
import com.web3.management.entity.TmClient;
import com.web3.management.entity.TmCommand;
import com.web3.management.security.SecurityUtils;
import com.web3.management.service.AccountCredentialService;
import com.web3.management.service.OperationLogService;
import com.web3.management.service.TmClientService;
import com.web3.management.service.TmCommandService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 管理后台中的 Tampermonkey 客户端相关接口
 */
@Slf4j
@RestController
@RequestMapping("/api/accounts/{accountId}")
@RequiredArgsConstructor
@Validated
public class AccountTmController {

    private final TmClientService tmClientService;
    private final TmCommandService tmCommandService;
    private final AccountCredentialService accountCredentialService;
    private final OperationLogService operationLogService;
    @PostMapping("/clients")
    public ApiResponse<ClientBindingResponse> bindClient(@PathVariable @Min(1) Integer accountId,
                                                         @Valid @RequestBody BindClientRequest request) {
        SecurityUtils.requireAdmin();
        TmClient client = tmClientService.bindClient(accountId, request.getClientId(), request.getRemark());
        operationLogService.record("BIND_TM_CLIENT", "ACCOUNT", accountId,
                String.format("绑定客户端 %s", client.getClientId()));
        ClientBindingResponse response = new ClientBindingResponse(client.getClientId(), accountId,
                client.getStatus(), client.getLastSeenAt());
        return ApiResponse.success("客户端绑定成功", response);
    }

    @DeleteMapping("/clients/{clientId}")
    public ApiResponse<Void> unbindClient(@PathVariable @Min(1) Integer accountId,
                                          @PathVariable @NotBlank String clientId) {
        SecurityUtils.requireAdmin();
        tmClientService.unbindClient(accountId, clientId);
        operationLogService.record("UNBIND_TM_CLIENT", "ACCOUNT", accountId,
                String.format("解绑客户端 %s", clientId));
        return ApiResponse.success("客户端解绑成功", null);
    }

    @PostMapping("/commands")
    public ApiResponse<Void> createCommand(@PathVariable @Min(1) Integer accountId,
                                           @Valid @RequestBody CommandCreateRequest request) {
        SecurityUtils.requireAdmin();
        TmCommand command = tmCommandService.createCommand(accountId, request.getType(), request.getPayload());
        operationLogService.record("CREATE_TM_COMMAND", "ACCOUNT", accountId,
                String.format("创建指令 %s, commandId=%d", request.getType(), command.getId()));
        return ApiResponse.success("指令创建成功", null);
    }

    @GetMapping("/credential-logs")
    public ApiResponse<List<AccountCredentialLogResponse>> listCredentialLogs(@PathVariable @Min(1) Integer accountId) {
        SecurityUtils.requireAdmin();
        List<AccountCredentialLog> logs = accountCredentialService.findRecent(accountId);
        List<AccountCredentialLogResponse> responses = logs.stream()
                .map(log -> new AccountCredentialLogResponse(log.getId(), log.getCaptureType(), log.getStatus(),
                        log.getMessage(), log.getClientId(), log.getPayload(), log.getCapturedAt()))
                .collect(Collectors.toList());
        return ApiResponse.success(responses);
    }
}
